//
//  JCWWaveProgressView.swift
//  JCWWaveProgressView
//
//  Created by wll on 2018/1/9.
//  Copyright © 2018年 wll. All rights reserved.
//  波动进度视图--代码


import UIKit

///进度阈值
private let _threshold: CGFloat = 100
///背景色
private let _bgColor: UIColor = Normal_CCCColor
///填充色
private let _fillColor: UIColor = ColorFromRGBHex_WL(0xff4a08)


class JCWWaveProgressView: UIView {

    ///更新函数
    open func wl_setProgress( _ progress: CGFloat, _ status: JCWProductStatus?) {
        self.progress = progress
        if status == .prepareSale {//预售中 20
            self.waveLayer.isHidden = true
            self.displayLink.isPaused = true
            self.backgroundColor = _bgColor
        }else if status == .saling{//募集中 30
            self.waveLayer.isHidden = false
            self.backgroundColor = _bgColor
            self.startAnimation()
            self.displayLink.isPaused = false
//            self.progressLab.text = "\(Int(progress))%"
            self.progressLab.dd_setNumber(NSNumber(integerLiteral: Int(progress)), duration: 1.4, format: "%.0f%%")
            
        }else{//已售罄
            self.waveLayer.isHidden = true
            self.displayLink.isPaused = true
            self.backgroundColor = _fillColor
        }
    }
    

    ///记录值
    private var controlX: CGFloat = 0
    private var progress: CGFloat = 0
    
    //MARK:构造函数
    convenience init () {
        self.init(frame: CGRect.zero)
        self.createUI()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.createUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func createUI() {
        
        self.backgroundColor = _bgColor
        self.clipsToBounds = true

        self.layer.addSublayer(self.waveLayer)
        self.addSubview(self.progressLab)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.cornerRadius = self.bounds.size.width/2
        self.progressLab.frame = self.bounds
        self.waveLayer.frame = self.bounds
    }

    //MARK:动画相关
    ///开启动画
    @objc private func startAnimation() {

//        正弦型函数解析式：y=Asin（ωx+φ）+k
//        各常数值对函数图像的影响：
//        φ（初相位）：决定波形与X轴位置关系或横向移动距离（左加右减）
//        ω：决定周期（最小正周期T=2π/|ω|）
//        A：决定峰值（即纵向拉伸压缩的倍数）
//        k：表示波形在Y轴的位置关系或纵向移动距离（上加下减
        let persent: CGFloat = 1 - min(1,self.progress/_threshold)
        let wh: CGFloat = self.bounds.size.width
        let s_ω: CGFloat = CGFloat(2.5*Double.pi)/wh
        let s_k: CGFloat = wh * persent
        var s_φ: CGFloat = 0.0
        let s_A: CGFloat = 2
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: s_k))
        s_φ = self.controlX
        
        var x: CGFloat = 0
        while x <= wh {
            let y = s_A * sin(s_ω * x + s_φ) + s_k
            path.addLine(to: CGPoint(x: x, y: y))
            x += 2
        }
        
        path.addLine(to: CGPoint(x: wh, y: 0))
        path.addLine(to: CGPoint(x: 0, y: 0))
        path.close()
        self.controlX += CGFloat(0.3 / Double.pi)//可控制频率

        self.waveLayer.path = path.cgPath
    }
    
    
    //MARK:懒加载
    
    ///波纹线
    open lazy var waveLayer: CAShapeLayer = {
        let temp = CAShapeLayer()
        temp.backgroundColor = _fillColor.cgColor
        temp.fillColor = _bgColor.cgColor
        return temp
    }()
    
    ///文字标签
    public lazy var progressLab: UILabel = {
        let temp = UILabel()
        temp.textColor = UIColor.white
        temp.font = UIFont.systemFont(ofSize: 11)
        temp.textAlignment = .center
        return temp
    }()
    
    ///定时器
    lazy var displayLink: CADisplayLink = {
        let temp = CADisplayLink(target: self, selector: #selector(startAnimation))
        temp.add(to: RunLoop.current, forMode: .commonModes)
        temp.isPaused = true
        return temp
    }()
}
